import { getQuestionsAPi } from "@/api";
import React, { useEffect, useState, TouchEvent } from "react";
import { useLocation } from "react-router-dom";
import CalendarViewMonthIcon from "@mui/icons-material/CalendarViewMonth";
import Chioce from "./components/Chioce";
import Fill from "./components/Fill";
import "./practise.less";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";

const chioces = ["one", "check", "many"];

export default function Practise() {
  // 得到从 select 页面 带过来的数据
  const location = useLocation();
  const state = location.state as IQuetionData;
  // 题目的数组
  const [qsList, setQSList] = useState<IQuestionResponse[]>([]);
  // 当前是第几个题目
  const [current, setCurrent] = useState(0);
  // console.log(location.state);
  // 向服务器发请求，得到一个题目的数组
  useEffect(() => {
    getQuestionsAPi(state).then((res) => {
      if (res.errCode === 0) {
        // 把 题目的数组渲染出来
        // console.log(res.data);
        setQSList(res.data);
      }
    });
  }, []);

  // let startX = 0,
  //   endX = 0;
  // // 实现滑动
  // const touchStart = (e: TouchEvent<HTMLDivElement>) => {
  //   // console.log(e.touches[0].clientX);
  //   startX = e.touches[0].clientX;
  // };

  // const touchEnd = (e: TouchEvent<HTMLDivElement>) => {
  //   // console.log(e.changedTouches[0].clientX);
  //   endX = e.changedTouches[0].clientX;

  //   // 滑动要有一定的距离才行
  //   if (Math.abs(startX - endX) >= 20) {
  //     // 判断 如果 startX > endX 就是向左 ， 让题目的索引 + 1
  //     if (startX > endX) {
  //       setCurrent(
  //         current + 1 >= qsList.length - 1 ? qsList.length - 1 : current + 1
  //       );
  //     } else {
  //       setCurrent(current - 1 <= 0 ? 0 : current - 1);
  //     }
  //   }
  // };

  return (
    <div className="practise">
      <div className="flex top">
        <CalendarViewMonthIcon />
        <span>
          {current + 1} / {qsList.length}
        </span>
      </div>
      {/* <div className="contain">
        <div
          className="qs-list"
          onTouchStart={(e) => touchStart(e)}
          onTouchEnd={(e) => touchEnd(e)}
          style={{
            width: qsList.length * 100 + "vw",
            transform: `translate(-${100 * current}vw)`,
          }}
        >
          {qsList.map((item) =>
            chioces.includes(item.questionType) ? (
              <Chioce key={item.id} data={item} />
            ) : (
              <Fill key={item.id} />
            )
          )}
        </div>
      </div> */}

      {/* 这里直接使用 swiper 实现题目切换 */}
      <Swiper onSlideChange={(e) => setCurrent(e.activeIndex)}>
        {qsList.map((item) => (
          <SwiperSlide key={item.id}>
            {chioces.includes(item.questionType) ? (
              <Chioce data={item} actionCode={state.actionCode} />
            ) : (
              <Fill data={item} actionCode={state.actionCode} />
            )}
          </SwiperSlide>
        ))}
      </Swiper>
    </div>
  );
}
